import { Modal, Spin, Table, Space, Pagination, Skeleton } from 'antd';
import { FC, useCallback, useEffect, useMemo, useState } from 'react';

import { FilterDialogProps, TableSelectedRowKeys, TableSelectedRows } from '../interface';
import {
  triggerTableSelectedRows,
  triggerConvertSearchParams,
  triggerConvertDataSource,
  triggerTableCheckboxRowProps,
} from '../triggerPlugin';
import { createSchemaFormRender } from '@/components/schema-form-render';
import { SchemaFormSearchContent } from '@/components/schema-form-render/components/schema-form-content';
import SearchButton from '@/biz-components/Button/search';
import FormResetButton from '@/biz-components/Button/form-reset';
import { useImmer } from 'use-immer';
import { useGetPageMeta,  useRefresh } from '../hooks';
import { useGetValue, getValue } from '../utils';
import request from '@ey-utils/utils/services/request';

const FilterDialog: FC<FilterDialogProps> = ({
  visible,
  onOk,
  onCancel,
  title,
  extraSearchParams,
  formCode,
  convertSearchType,
  convertTableDataSourceType,
  convertTableSelectedRowsType,
  tableCheckboxRowPropsType,
  isMultiple,
  schema,
  url,
  method,
  fieldValidator,
  ...restTableProps
}) => {
  const { columns, jsonSchema, initLoading } = useGetPageMeta(formCode);
  const { form, Render: RenderSc } = useMemo(() => createSchemaFormRender(), []);

  const [refresh, updateRefresh] = useRefresh();

  const path = useGetValue();

  const [loading, setLoading] = useState<boolean>(false);

  const [pageConfig, setPageConfig] = useImmer({
    total: 0,
    current: 1,
    pageSize: 10,
  });

  const [dataSource, setDataSource] = useState([]);

  const [selectedRowKeys, setSelectedRowKeys] = useState<TableSelectedRowKeys>([]);

  const [selectedRows, setSelectedRows] = useState<TableSelectedRows>([]);

  const { current, pageSize } = pageConfig;

  const handleSelectChange = (rowKeys: TableSelectedRowKeys, rows: TableSelectedRows) => {
    setSelectedRowKeys(rowKeys);
    setSelectedRows(rows);
  };

  const handleOk = () => {
    if (!selectedRows.length) {
      return;
    }
    onOk?.(triggerTableSelectedRows(convertTableSelectedRowsType, selectedRows));
    // @ts-ignore
    onCancel?.();
  };

  const search = useCallback(
    (pageNo: number, size: number) => {
      if (!(url || method)) {
        return;
      }
      form
        .submit((values) => {
          const formValues = getValue(values, path);
          const params = {
            ...extraSearchParams,
            ...formValues,
            pageCode: formCode,
          };
          setLoading(true);
          request(url, {
            method,
            data: {
              pageNo,
              pageSize: size,
              queryKeys: triggerConvertSearchParams(convertSearchType, params),
            },
          })
            .then((res: any) => {
              const { result } = res;
              const { totalPages, content, total } = result;

              setSelectedRowKeys([]);
              setSelectedRows([]);
              setDataSource(triggerConvertDataSource(convertTableDataSourceType, content));

              setPageConfig((draft) => {
                draft.total = totalPages || total;
              });
            })
            .finally(() => {
              setLoading(false);
            });
        })
        .finally(() => {});
    },
    [url, method, extraSearchParams, formCode],
  );

  const handleSearch = () => {
    setPageConfig((draft) => {
      draft.current = 1;
    });
    updateRefresh();
  };

  const handleReset = () => {
    form.reset();
  };

  const handlePaginationChange = (
    currentPage: number | undefined,
    currentPageSize: number | undefined,
  ) => {
    setPageConfig((draft) => {
      draft.current = currentPage || 1;
      draft.pageSize = currentPageSize || 10;
    });
  };

  const rowSelection = {
    type: isMultiple ? 'checkbox' : 'radio',
    selectedRowKeys,
    onChange: handleSelectChange,
    getCheckboxProps: (record: any) =>
      triggerTableCheckboxRowProps(tableCheckboxRowPropsType, record),
  };

  useEffect(() => {
    setPageConfig((draft) => {
      draft.current = 1;
    });
    updateRefresh();
  }, [extraSearchParams, updateRefresh]);

  useEffect(() => {
    if (visible) {
      search(current, pageSize);
    }
  }, [visible, current, pageSize, search, refresh]);

  const renderPaginationTotal = (total: number, range: number[]): string =>
    `总共${total}条,当前第${range[0]}至${range[1]}`;

  return (
    <Modal
      title={title}
      visible={visible}
      onCancel={onCancel}
      onOk={handleOk}
      width={1080}
      closable={false}
      maskClosable={false}
      bodyStyle={{
        overflowY: 'auto',
      }}
    >
      <Skeleton active loading={initLoading}>
        <Spin spinning={loading} tip="搜索中。。。。">
          <SchemaFormSearchContent
            footer={
              <Space>
                <SearchButton onClick={handleSearch} />
                <FormResetButton onReset={handleReset} />
              </Space>
            }
          >
            {RenderSc && <RenderSc schema={schema || jsonSchema} />}
          </SchemaFormSearchContent>

          <Table
            // @ts-ignore
            rowSelection={rowSelection}
            scroll={{
              y: 400,
            }}
            columns={columns}
            rowKey="id"
            {...restTableProps}
            dataSource={dataSource}
            pagination={false}
          />

          <Pagination
            size="small"
            {...pageConfig}
            onChange={handlePaginationChange}
            onShowSizeChange={handlePaginationChange}
            showTotal={renderPaginationTotal}
            showSizeChanger
            showQuickJumper
          />
        </Spin>
      </Skeleton>
    </Modal>
  );
};

FilterDialog.defaultProps = {
  isMultiple: false,
};

export default FilterDialog;
